# 文件路径: backend/api/intervention_api.py
# 干预操作记录API（完整实现）
from flask import Blueprint, request, jsonify, send_file
from backend.infrastructure.database import db
from backend.models.intervention import InterventionRecord
from backend.models.student import Student
from io import BytesIO, StringIO  # 新增导入 StringIO
import pandas as pd
from datetime import datetime
from backend.models.intervention_log import InterventionRecordLog  # 新增导入日志模型
from flask import current_app
import json
from backend.config.config_manager import ConfigManager
from backend.services.unified_log_service import log_service  # ✅新增：统一日志服务

# 初始化配置管理器
config_manager = ConfigManager()
LOG_CONFIG = config_manager.get_unified_log_config()
LOG_FRONTEND_CONFIG = config_manager.get_log_frontend_config()

intervention_api = Blueprint('intervention_api', __name__, url_prefix='/api/intervention_records')

def parse_datetime(dt_str):
    """解析前端提交的datetime-local字符串为datetime对象"""
    try:
        if not dt_str:
            return None
        if isinstance(dt_str, datetime):
            return dt_str
        # 兼容前端"2024-05-20T10:00"或"2024-05-20 10:00"
        return datetime.strptime(dt_str.replace('T', ' '), '%Y-%m-%d %H:%M')
    except Exception:
        return None

# 查询学生所有干预记录（按时间倒序），支持分页 - 配置驱动版本
@intervention_api.route('/list', methods=['GET'])
def list_records():
    try:
        student_id = request.args.get('student_id', type=int)
        if not student_id:
            return jsonify({"success": False, "message": "缺少student_id参数", "data": None}), 400
            
        # ✅ 使用配置驱动的分页参数
        pagination_config = config_manager.get_intervention_api_pagination()
        
        page = request.args.get('page', type=int, default=pagination_config.get('default_page', 1))
        per_page = request.args.get('per_page', type=int, default=pagination_config.get('default_per_page', 10))
        max_per_page = pagination_config.get('max_per_page', 100)
        
        # 限制每页最大数量
        if per_page > max_per_page:
            per_page = max_per_page
            
        query = (InterventionRecord.query
                   .filter_by(student_id=student_id)
                   .order_by(InterventionRecord.operation_time.desc()))
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        records = pagination.items
        
        return jsonify({
            "success": True,
            "data": [r.to_dict() for r in records],
            "total": pagination.total,
            "page": page,
            "per_page": per_page
        })
        
    except Exception as e:
        return jsonify({"success": False, "message": f"获取干预记录列表失败: {str(e)}", "data": None}), 500

# 获取单条干预记录详情
@intervention_api.route('/<int:record_id>', methods=['GET'])
def get_record(record_id):
    record = InterventionRecord.query.get_or_404(record_id)
    return jsonify({"success": True, "data": record.to_dict()})


# 新建干预记录 - 配置驱动版本
@intervention_api.route('', methods=['POST'])
def create_record():
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "message": "请求数据为空", "data": None}), 400
            
        # ✅ 使用配置驱动的验证
        validation_config = config_manager.get_intervention_api_validation_config()
        required_fields = validation_config.get('required_fields', [])
        
        # 验证必填字段
        for field in required_fields:
            if not data.get(field):
                return jsonify({"success": False, "message": f"缺少必填字段: {field}", "data": None}), 400
        
        # ✅ 使用配置驱动的默认值
        defaults = config_manager.get_intervention_api_defaults()
        for field, default_value in defaults.items():
            if field not in data or data[field] is None:
                data[field] = default_value
        
        # ✅ 获取学生历史累计值和序号（修复：统计实际次数而不是最新记录的累计值）
        student_id = data.get('student_id')
        if student_id:
            # 查询该学生所有历史记录，统计每种干预类型的实际次数
            from sqlalchemy import func
            
            # 统计每种干预类型的实际次数
            intervention_counts = (db.session.query(
                InterventionRecord.intervention_type,
                func.count(InterventionRecord.id).label('count')
            )
            .filter_by(student_id=student_id)
            .group_by(InterventionRecord.intervention_type)
            .all())
            
            # 获取该学生的总记录数（用于global_sequence）
            total_records = InterventionRecord.query.filter_by(student_id=student_id).count()
            
            # 获取该学生当前干预类型的记录数（用于session_number）
            current_intervention_type = data.get('intervention_type', '耳穴压丸')
            current_type_records = InterventionRecord.query.filter_by(
                student_id=student_id, 
                intervention_type=current_intervention_type
            ).count()
            
            # 设置序号字段
            data['session_number'] = current_type_records + 1  # 当前类型的第几次
            data['global_sequence'] = total_records + 1       # 全局第几次
            
            # ✅ 修复：初始化累计值为历史统计值，然后为当前类型+1
            data['guasha_count'] = 0
            data['aigiu_count'] = 0
            data['erxue_yawan_count'] = 0
            data['zhongyao_xunzheng_count'] = 0
            data['rejiu_training_count'] = 0
            data['reci_pulse_count'] = 0
            data['baoguan_count'] = 0
            
            # 根据实际统计结果设置累计值
            for intervention_type, count in intervention_counts:
                if intervention_type == "刮痧":
                    data['guasha_count'] = count
                elif intervention_type == "艾灸":
                    data['aigiu_count'] = count
                elif intervention_type == "耳穴压丸":
                    data['erxue_yawan_count'] = count
                elif intervention_type == "中药熏蒸":
                    data['zhongyao_xunzheng_count'] = count
                elif intervention_type == "热灸训练":
                    data['rejiu_training_count'] = count
                elif intervention_type == "热磁脉冲":
                    data['reci_pulse_count'] = count
                elif intervention_type == "拔罐":
                    data['baoguan_count'] = count
            
            # ✅ 修复：为当前干预类型累加1
            if current_intervention_type == "刮痧":
                data['guasha_count'] += 1
            elif current_intervention_type == "艾灸":
                data['aigiu_count'] += 1
            elif current_intervention_type == "耳穴压丸":
                data['erxue_yawan_count'] += 1
            elif current_intervention_type == "中药熏蒸":
                data['zhongyao_xunzheng_count'] += 1
            elif current_intervention_type == "热灸训练":
                data['rejiu_training_count'] += 1
            elif current_intervention_type == "热磁脉冲":
                data['reci_pulse_count'] += 1
            elif current_intervention_type == "拔罐":
                data['baoguan_count'] += 1

        record = InterventionRecord(
            student_id=data.get('student_id'),
            intervention_date=data.get('intervention_date'),
            operation_time=data.get('operation_time'),
            intervention_type=data.get('intervention_type'),
            operator=data.get('operator'),
            duration_minutes=data.get('duration_minutes'),
            operation_location=data.get('operation_location'),
            operation_tools=data.get('operation_tools', []),
            consumed_materials=data.get('consumed_materials', []),
            operation_sites=data.get('operation_sites', []),
            details=data.get('details'),
            acupoints=data.get('acupoints', []),
            press_methods=data.get('press_methods', []),
            press_strength=data.get('press_strength'),
            press_frequency=data.get('press_frequency'),
            immediate_effect=data.get('immediate_effect'),
            cooperation_level=data.get('cooperation_level'),
            patient_reaction=data.get('patient_reaction'),
            # 24个新增专用字段
            scraping_intensity=data.get('scraping_intensity'),
            scraping_direction=data.get('scraping_direction'),
            scraping_duration=data.get('scraping_duration'),
            skin_reaction=data.get('skin_reaction'),
            moxibustion_type=data.get('moxibustion_type'),
            temperature_level=data.get('temperature_level'),
            moxibustion_distance=data.get('moxibustion_distance'),
            heat_sensation=data.get('heat_sensation'),
            steam_temperature=data.get('steam_temperature'),
            medicine_formula=data.get('medicine_formula'),
            steam_intensity=data.get('steam_intensity'),
            comfort_level=data.get('comfort_level'),
            intensity_level=data.get('intensity_level'),
            treatment_mode=data.get('treatment_mode'),
            temperature_feedback=data.get('temperature_feedback'),
            training_effect=data.get('training_effect'),
            pulse_frequency=data.get('pulse_frequency'),
            magnetic_intensity=data.get('magnetic_intensity'),
            pulse_pattern=data.get('pulse_pattern'),
            sensation_feedback=data.get('sensation_feedback'),
            suction_strength=data.get('suction_strength'),
            cupping_method=data.get('cupping_method'),
            skin_color_change=data.get('skin_color_change'),
            cupping_marks=data.get('cupping_marks'),
            # ✅ 设置序号字段
            session_number=data.get('session_number', 1),
            global_sequence=data.get('global_sequence', 1),
            # ✅ 设置历史累计值
            guasha_count=data.get('guasha_count', 0),
            aigiu_count=data.get('aigiu_count', 0),
            erxue_yawan_count=data.get('erxue_yawan_count', 0),
            zhongyao_xunzheng_count=data.get('zhongyao_xunzheng_count', 0),
            rejiu_training_count=data.get('rejiu_training_count', 0),
            reci_pulse_count=data.get('reci_pulse_count', 0),
            baoguan_count=data.get('baoguan_count', 0)
        )
        
        # ✅ 修复：不调用auto_fill_fields()，因为我们已经手动设置了累计值
        # 只调用其他自动填充逻辑
        try:
            # 只设置数据年份和数据来源，不更新累计统计
            if record.intervention_date is not None:
                if isinstance(record.intervention_date, str):
                    try:
                        from datetime import datetime
                        date_obj = datetime.strptime(record.intervention_date, '%Y-%m-%d').date()
                        record.intervention_date = date_obj
                    except ValueError:
                        pass
                
                if hasattr(record.intervention_date, 'year') and not isinstance(record.intervention_date, str):
                    record.data_year = str(record.intervention_date.year)
            
            if record.upload_source is None or not record.upload_source:
                record.upload_source = 'PC端'
        except Exception as e:
            current_app.logger.warning(f"自动填充字段失败: {e}")
        
        # 保存到数据库
        db.session.add(record)
        db.session.flush()  # 获取记录ID
        
        # ✅ 修复：使用与视力模块相同的日志记录方式
        try:
            InterventionRecordLog.log_create(
                record=record,
                operator=data.get('operator', '系统'),
                ip_address=request.remote_addr
            )
        except Exception as log_error:
            print(f"创建日志失败: {log_error}")

        db.session.commit()
        
        # ✅ 使用配置驱动的消息
        messages = config_manager.get_intervention_api_messages()
        success_message = messages.get('create_success', '干预记录创建成功')
        
        return jsonify({"success": True, "message": success_message, "data": record.to_dict()})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"创建干预记录失败: {str(e)}", "data": None}), 500

# 修改干预记录 - 配置驱动版本
@intervention_api.route('/<int:record_id>', methods=['PUT'])
def update_record(record_id):
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "message": "请求数据为空", "data": None}), 400
            
        record = InterventionRecord.query.get_or_404(record_id)
        
        # ✅ 修复：保存更新前的数据（与视力模块一致）
        old_data = record.to_dict()
        
        # ✅ 使用配置驱动的验证
        validation_config = config_manager.get_intervention_api_validation_config()
        
        # 基础字段更新
        record.intervention_type = data.get('intervention_type', record.intervention_type)
        record.intervention_date = data.get('intervention_date', record.intervention_date)
        record.operation_time = data.get('operation_time', record.operation_time)
        record.operator = data.get('operator', record.operator)
        record.duration_minutes = data.get('duration_minutes', record.duration_minutes)
        record.operation_location = data.get('operation_location', record.operation_location)
        record.operation_tools = data.get('operation_tools', record.operation_tools)
        record.consumed_materials = data.get('consumed_materials', record.consumed_materials)
        record.operation_sites = data.get('operation_sites', record.operation_sites)
        record.details = data.get('details', record.details)
        record.acupoints = data.get('acupoints', record.acupoints)
        record.press_methods = data.get('press_methods', record.press_methods)
        record.press_strength = data.get('press_strength', record.press_strength)
        record.press_frequency = data.get('press_frequency', record.press_frequency)
        record.immediate_effect = data.get('immediate_effect', record.immediate_effect)
        record.cooperation_level = data.get('cooperation_level', record.cooperation_level)
        record.patient_reaction = data.get('patient_reaction', record.patient_reaction)
        
        # 24个新增专用字段更新
        record.scraping_intensity = data.get('scraping_intensity', record.scraping_intensity)
        record.scraping_direction = data.get('scraping_direction', record.scraping_direction)
        record.scraping_duration = data.get('scraping_duration', record.scraping_duration)
        record.skin_reaction = data.get('skin_reaction', record.skin_reaction)
        record.moxibustion_type = data.get('moxibustion_type', record.moxibustion_type)
        record.temperature_level = data.get('temperature_level', record.temperature_level)
        record.moxibustion_distance = data.get('moxibustion_distance', record.moxibustion_distance)
        record.heat_sensation = data.get('heat_sensation', record.heat_sensation)
        record.steam_temperature = data.get('steam_temperature', record.steam_temperature)
        record.medicine_formula = data.get('medicine_formula', record.medicine_formula)
        record.steam_intensity = data.get('steam_intensity', record.steam_intensity)
        record.comfort_level = data.get('comfort_level', record.comfort_level)
        record.intensity_level = data.get('intensity_level', record.intensity_level)
        record.treatment_mode = data.get('treatment_mode', record.treatment_mode)
        record.temperature_feedback = data.get('temperature_feedback', record.temperature_feedback)
        record.training_effect = data.get('training_effect', record.training_effect)
        record.pulse_frequency = data.get('pulse_frequency', record.pulse_frequency)
        record.magnetic_intensity = data.get('magnetic_intensity', record.magnetic_intensity)
        record.pulse_pattern = data.get('pulse_pattern', record.pulse_pattern)
        record.sensation_feedback = data.get('sensation_feedback', record.sensation_feedback)
        record.suction_strength = data.get('suction_strength', record.suction_strength)
        record.cupping_method = data.get('cupping_method', record.cupping_method)
        record.skin_color_change = data.get('skin_color_change', record.skin_color_change)
        record.cupping_marks = data.get('cupping_marks', record.cupping_marks)
        
        # ✅ 修复：更新时不调用auto_fill_fields()，避免累计值被重新计算
        # 只更新数据年份和数据来源，不更新累计统计
        try:
            if record.intervention_date is not None:
                if isinstance(record.intervention_date, str):
                    try:
                        from datetime import datetime
                        date_obj = datetime.strptime(record.intervention_date, '%Y-%m-%d').date()
                        record.intervention_date = date_obj
                    except ValueError:
                        pass
                
                if hasattr(record.intervention_date, 'year') and not isinstance(record.intervention_date, str):
                    record.data_year = str(record.intervention_date.year)
            
            if record.upload_source is None or not record.upload_source:
                record.upload_source = 'PC端编辑'
        except Exception as e:
            current_app.logger.warning(f"自动填充字段失败: {e}")
        
        # 更新时间戳
        record.updated_at = datetime.now()
        
        # ✅ 修复：使用与视力模块相同的日志记录方式
        try:
            InterventionRecordLog.log_update(
                record=record,
                old_data=old_data,
                operator=data.get('operator', '系统'),
                ip_address=request.remote_addr
            )
        except Exception as log_error:
            print(f"更新日志失败: {log_error}")
        
        # 保存到数据库
        db.session.commit()
        
        # ✅ 使用配置驱动的消息
        messages = config_manager.get_intervention_api_messages()
        success_message = messages.get('update_success', '干预记录更新成功')
        
        return jsonify({"success": True, "message": success_message, "data": record.to_dict()})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"更新干预记录失败: {str(e)}", "data": None}), 500

# 删除干预记录 - 配置驱动版本
@intervention_api.route('/<int:record_id>', methods=['DELETE'])
def delete_record(record_id):
    try:
        record = InterventionRecord.query.get(record_id)
        if not record:
            # ✅ 使用配置驱动的消息
            messages = config_manager.get_intervention_api_messages()
            not_found_message = messages.get('not_found', '干预记录不存在')
            return jsonify({"success": False, "message": not_found_message, "data": None}), 404
        
        # ✅ 修复：使用与视力模块相同的日志记录方式
        try:
            InterventionRecordLog.log_delete(
                record=record,
                operator=record.operator,
                ip_address=request.remote_addr
            )
        except Exception as log_error:
            print(f"删除日志失败: {log_error}")
        
        db.session.delete(record)
        db.session.commit()
        
        # ✅ 使用配置驱动的消息
        messages = config_manager.get_intervention_api_messages()
        success_message = messages.get('delete_success', '干预记录删除成功')
        
        return jsonify({"success": True, "message": success_message, "data": None})
        
    except Exception as e:
        db.session.rollback()
        return jsonify({"success": False, "message": f"删除干预记录失败: {str(e)}", "data": None}), 500

# 导出干预记录
@intervention_api.route('/export', methods=['GET'])
def export_records():
    try:
        student_id = request.args.get('student_id', type=int)
        export_type = request.args.get('type', 'xlsx')
        
        if not student_id:
            return jsonify({"success": False, "message": "缺少student_id参数", "data": None}), 400
            
        # 获取学生信息
        student = Student.query.get_or_404(student_id)
        
        # 获取该学生的所有干预记录
        records = InterventionRecord.query.filter_by(student_id=student_id)\
                                         .order_by(InterventionRecord.operation_time.desc())\
                                         .all()
        
        if not records:
            return jsonify({"success": False, "message": "该学生暂无干预记录", "data": None}), 404
        
        # 获取字段显示映射
        field_mapping = config_manager.get_field_display_mapping()
        
        # 定义弃用字段列表（不在导出中显示）
        deprecated_fields = [
            'guasha', 'aigiu', 'erxue_yawan', 'zhongyao_xunzheng', 'rejiu_training', 'reci_pulse', 'baoguan',
            'scraping_intensity', 'scraping_direction', 'scraping_duration',
            'moxibustion_type', 'moxibustion_distance',
            'cupping_method'
        ]
        
        # 准备导出数据
        export_data = []
        for record in records:
            record_dict = record.to_dict()
            # 处理列表字段
            for field in ['operation_tools', 'consumed_materials', 'operation_sites', 'acupoints', 'press_methods']:
                if isinstance(record_dict.get(field), list):
                    record_dict[field] = ', '.join(record_dict[field]) if record_dict[field] else ''
            export_data.append(record_dict)
        
        # 创建DataFrame
        df_export = pd.DataFrame(export_data)
        
        # 过滤掉弃用字段
        existing_deprecated_fields = [field for field in deprecated_fields if field in df_export.columns]
        if existing_deprecated_fields:
            df_export = df_export.drop(columns=existing_deprecated_fields)
        
        # 过滤掉所有值都为空的列
        df_export = df_export.dropna(axis=1, how='all')
        # 过滤掉所有值都为空字符串的列
        for col in df_export.columns:
            if df_export[col].astype(str).str.strip().eq('').all():
                df_export = df_export.drop(columns=[col])
        
        # 将英文字段名转换为中文显示名
        column_mapping = {}
        for col in df_export.columns:
            chinese_name = field_mapping.get(col, col)
            column_mapping[col] = chinese_name
        
        df_export = df_export.rename(columns=column_mapping)
        
        # 生成文件名
        filename = f"{student.name}_{student.education_id}_干预记录.{'csv' if export_type == 'csv' else 'xlsx'}"
        
        # 导出文件
        output = BytesIO()
        if export_type == 'csv':
            csv_buf = StringIO()
            df_export.to_csv(csv_buf, index=False, encoding='utf-8-sig')
            output.write(csv_buf.getvalue().encode('utf-8-sig'))
            output.seek(0)
            return send_file(output, mimetype="text/csv", as_attachment=True, download_name=filename)
        else:
            with pd.ExcelWriter(output, engine='openpyxl') as writer:  # type: ignore
                df_export.to_excel(writer, sheet_name='干预记录', index=False)
            output.seek(0)
            return send_file(output, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                             as_attachment=True, download_name=filename)
        
    except Exception as e:
        return jsonify({"success": False, "message": f"导出失败: {str(e)}", "data": None}), 500

# 导出单条干预记录
@intervention_api.route('/export_one', methods=['GET'])
def export_one_record():
    try:
        record_id = request.args.get('record_id', type=int)
        export_type = request.args.get('type', 'xlsx')
        
        if not record_id:
            return jsonify({"success": False, "message": "缺少record_id参数", "data": None}), 400
            
        # 获取干预记录
        record = InterventionRecord.query.get_or_404(record_id)
        
        # 获取学生信息
        student = Student.query.get_or_404(record.student_id)
        
        # 获取字段显示映射
        field_mapping = config_manager.get_field_display_mapping()
        
        # 定义弃用字段列表（不在导出中显示）
        deprecated_fields = [
            'guasha', 'aigiu', 'erxue_yawan', 'zhongyao_xunzheng', 'rejiu_training', 'reci_pulse', 'baoguan',
            'scraping_intensity', 'scraping_direction', 'scraping_duration',
            'moxibustion_type', 'moxibustion_distance',
            'cupping_method'
        ]
        
        # 准备导出数据
        record_dict = record.to_dict()
        # 处理列表字段
        for field in ['operation_tools', 'consumed_materials', 'operation_sites', 'acupoints', 'press_methods']:
            if isinstance(record_dict.get(field), list):
                record_dict[field] = ', '.join(record_dict[field]) if record_dict[field] else ''
        
        # 过滤掉空值字段和弃用字段
        filtered_dict = {}
        for key, value in record_dict.items():
            if key not in deprecated_fields and value is not None and str(value).strip() != '':
                chinese_name = field_mapping.get(key, key)
                filtered_dict[chinese_name] = value
        
        # 创建DataFrame
        df_export = pd.DataFrame([filtered_dict])
        
        # 生成标题
        title = f"学生：{student.name}（{student.education_id}） - 干预记录详情"
        
        # 生成文件名
        filename = f"{student.name}_单条干预记录.{ 'csv' if export_type == 'csv' else 'xlsx'}"
        
        # 创建内存文件对象
        from io import BytesIO
        output = BytesIO()
        
        if export_type == 'csv':
            csv_buf = StringIO()
            csv_buf.write(title + '\n')
            df_export.to_csv(csv_buf, index=False, encoding='utf-8-sig')
            output.write(csv_buf.getvalue().encode('utf-8-sig'))
            output.seek(0)
            return send_file(output, mimetype="text/csv", as_attachment=True, download_name=filename)
        else:
            with pd.ExcelWriter(output, engine='openpyxl') as writer:  # type: ignore
                pd.DataFrame([[title]]).to_excel(writer, sheet_name='Sheet1', index=False, header=False, startrow=0)
                df_export.to_excel(writer, sheet_name='Sheet1', index=False, header=True, startrow=2)
            output.seek(0)
            return send_file(output, mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                             as_attachment=True, download_name=filename)
                             
    except Exception as e:
        return jsonify({"success": False, "message": f"导出失败: {str(e)}", "data": None}), 500

# 查询日志
@intervention_api.route('/logs', methods=['GET'])
def get_logs():
    """获取单条干预记录的操作日志 - 使用统一日志服务"""
    record_id = request.args.get('record_id', type=int)
    
    # ✅ 修复：使用与视力模块相同的统一日志服务调用方式
    response_data, status_code = log_service.get_record_logs(
        LogModel=InterventionRecordLog,
        record_id=record_id,
        order_by_field='operation_time',
        config=LOG_FRONTEND_CONFIG
    )
    
    return jsonify(response_data), status_code

# 查询某学生所有干预记录的日志（含已删除）
@intervention_api.route('/logs_all', methods=['GET'])
def get_all_logs():
    """获取某学生的所有干预记录操作日志 - 使用统一日志服务"""
    student_id = request.args.get('student_id', type=int)
    
    # 获取学生姓名用于消息显示
    student_name = None
    if student_id:
        try:
            student = Student.query.get(student_id)
            if student:
                student_name = student.name
        except Exception:
            pass
    
    # ✅ 修复：使用与视力模块相同的统一日志服务调用方式
    response_data, status_code = log_service.get_student_all_logs(
        LogModel=InterventionRecordLog,
        student_id=student_id,
        order_by_field='operation_time',
        config=LOG_FRONTEND_CONFIG,
        student_name=student_name
    )
    
    return jsonify(response_data), status_code

# 恢复历史记录
@intervention_api.route('/restore', methods=['POST'])
def restore_record():
    """使用统一日志服务恢复干预记录"""
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "message": "请求数据为空", "data": None}), 400
        
        log_id = data.get('log_id')
        operator = data.get('operator', '系统')
        ip_address = request.remote_addr
        
        # ✅ 修复：使用与视力模块相同的统一日志服务调用方式
        response_data, status_code = log_service.restore_record(
            LogModel=InterventionRecordLog,
            RecordModel=InterventionRecord,
            log_id=log_id,
            operator=operator,
            ip_address=ip_address
        )
        
        return jsonify(response_data), status_code
        
    except Exception as e:
        print(f"Error in restore_record: {e}")
        import traceback
        traceback.print_exc()
        return jsonify({"success": False, "message": f"恢复失败: {str(e)}", "data": None}), 500

# 恢复已删除的干预记录
@intervention_api.route('/restore_deleted', methods=['POST'])
def restore_deleted_record():
    """恢复已删除的干预记录"""
    try:
        data = request.json
        if not data:
            return jsonify({"success": False, "message": "请求数据为空", "data": None}), 400
        
        log_id = data.get('log_id')
        operator = data.get('operator', '系统')
        ip_address = request.remote_addr
        
        # 查询删除日志记录
        log = InterventionRecordLog.query.get_or_404(log_id)
        
        if log.action != 'DELETE':
            return jsonify({"success": False, "message": "该日志不是删除操作"}), 400
        
        if not log.old_content:
            return jsonify({"success": False, "message": "日志中无可恢复的内容"}), 400
        
        # 解析原始数据
        try:
            old_data = json.loads(log.old_content)
        except json.JSONDecodeError:
            return jsonify({"success": False, "message": "日志数据格式错误"}), 400
        
        # 创建新记录
        new_record = InterventionRecord()
        
        # 恢复数据（排除id字段）
        for key, value in old_data.items():
            if key != 'id' and hasattr(new_record, key):
                setattr(new_record, key, value)
        
        # 保存新记录
        db.session.add(new_record)
        db.session.flush()  # 获取新记录ID
        
        # 记录恢复操作日志
        try:
            restore_log = InterventionRecordLog.log_restore(
                record_id=new_record.id,
                student_id=new_record.student_id,
                old_data={},  # 恢复前状态（记录不存在）
                restored_data=old_data,  # 恢复后状态
                operator=operator,
                ip_address=ip_address
            )
            if restore_log:
                db.session.add(restore_log)
        except Exception as log_error:
            print(f"记录恢复日志失败: {log_error}")
        
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '已删除的干预记录恢复成功',
            'data': new_record.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'message': str(e)}), 500

# 配置获取路由已迁移到 config_api.py，保持API架构统一
